package com.music.mysongs.server

import java.io.*
import java.net.InetAddress
import java.net.ServerSocket
import java.net.Socket
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

object ChatServer {
    private const val port: Int = 8080
    private val myList = ArrayList<Socket>()
    private var myServer: ServerSocket? = null
    private var myExecutor: ExecutorService? = null

    @JvmStatic
    fun main(args: Array<String>) {
        server()
    }

    private fun server() {
        try {
            myServer = ServerSocket(port)
            myExecutor = Executors.newCachedThreadPool()
            val address: InetAddress = InetAddress.getLocalHost()
            println("server=$address")
            while (true) {
                val client = myServer!!.accept()
                myList.add(client)
                myExecutor?.execute(SocketRun(client))
                println("client=$client")
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    class SocketRun(mSocket: Socket) : Runnable {
        private var read: BufferedReader? = null
        private var rSocket = mSocket

        init {
            try {
                read = BufferedReader(InputStreamReader(rSocket.getInputStream()))
                val msg = "当前在线${myList.size}人儿~"
                sendMsg(msg)
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }

        override fun run() {
            try {
                while (true) {
                    var msg: String
                    if (read?.readLine().also { msg = it.toString() } != null) {
                        if (msg == "bye") {
                            println("bye")
                            myList.remove(rSocket)
                            read?.close()
                            msg = "在线${myList.size}人儿 ~"
                            rSocket.close()
                            sendMsg(msg)
                            break
                        } else {
                            sendMsg(msg)
                        }
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        //为连接上服务端的每个客户端发送信息
        private fun sendMsg(send: String) {
            println("sendMsg=$send")
            for (index in 0 until myList.size) {
                try {
                    val pout = PrintWriter(
                        BufferedWriter(
                            OutputStreamWriter(myList[index].getOutputStream(), "UTF-8")
                        ), true
                    )
                    pout.println(send)
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
    }
}